package com.glorysoft.tonglingxjpda.ui.function.viewmodel

import android.os.Handler
import android.os.Looper
import androidx.databinding.ObservableArrayList
import com.glorysoft.hlgdpda.entity.ui.CallObserveBean
import com.glorysoft.tonglingxjpda.BR
import com.glorysoft.tonglingxjpda.R
import com.glorysoft.tonglingxjpda.base.BaseViewModel
import com.glorysoft.tonglingxjpda.base.Constant
import com.glorysoft.tonglingxjpda.entity.BatchListEntity
import com.glorysoft.tonglingxjpda.entity.DefectEntity
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.model.TaskRepository
import com.glorysoft.tonglingxjpda.utils.FileUtils
import com.glorysoft.tonglingxjpda.utils.SmbFileUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils
import jcifs.smb.SmbFile
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.io.File
import kotlin.concurrent.thread

/**
 * FileName: FinCheckViewModel
 * Author: XJH
 * Date: 2022/5/10 16:30
 * Description:
 * History:
 */
class FinCheckViewModel : BaseViewModel() {

    val batchTitle = arrayListOf("BatchID", "批次", "刻印号", "部件名称", "部件描述","数量","状态","Hold状态","工步描述","流程名称")

    private val defectRepository = TaskRepository()

    private val onCurrentIconClickListener = object : DefectViewModel.OnItemClickListener {
        override fun onItemClick(item: Any) {
            defUI.callObserve.value = CallObserveBean(2,item)
        }

    }

    //order 批次列表
    var finBatchItems = ObservableArrayList<BatchListEntity.BatchInfoEntity>()
    var finBatchBinding =
        ItemBinding.of<BatchListEntity.BatchInfoEntity>(BR.finBatchItem, R.layout.item_fin_batch_info)

    var defectDesc = arrayListOf<String>()
    var defectPos = arrayListOf<String>()
    var defectNum = arrayListOf<String>()
    private val handler = Handler(Looper.getMainLooper())

    var currentDefectItems = ObservableArrayList<DefectEntity.DefectInfoEntity>()
    var currentDefectBinding =
        ItemBinding.of<DefectEntity.DefectInfoEntity>(BR.defectItem, R.layout.item_defect_list).bindExtra(
            BR.onIconClick,onCurrentIconClickListener)

    var defectItems = ObservableArrayList<DefectEntity.DefectInfoEntity>()
    var defectBinding =
        ItemBinding.of<DefectEntity.DefectInfoEntity>(BR.defect2Item, R.layout.item_defect_list2)

    fun init(){
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","TRACKPICINFO")
        map.addProperty("OBJECTRRN",finBatchItems[0].OBJECTRRN)
        launchOnlyResult({
            val saveFinCheck = defectRepository.saveFinCheck(map)
            getDefectCode()
            if (saveFinCheck.PICINFOLIST.isNotEmpty()){
                downPic(saveFinCheck.PICINFOLIST)
            }
        })
    }

    private fun downPic(defectInfo: List<DefectEntity.DefectInfoEntity>) {
        defUI.callObserve.value = CallObserveBean(1,"FAIL")
        thread {
            defectInfo.forEach {
                    if (it.URL.isNotEmpty()){
                        if (SmbFileUtils.smbGet(it.URL, FileUtils.getLocalPathAndFileName(getApplication()))) {
                            val remoteFile = SmbFile(it.URL)
                            val fileName = remoteFile.name
                            it.localPath = FileUtils.getLocalPathAndFileName(getApplication()) + File.separator + fileName
                        }
                    }
                }


            handler.post {
                currentDefectItems.clear()
                defectItems.clear()
                defectInfo.forEach {
                    if (it.STEPNAME.isEmpty()){
                        defectItems.add(it)
                    }else{
                        currentDefectItems.add(it)
                    }
                }
                defUI.callObserve.value = CallObserveBean(0,"FAIL")
            }
        }

    }

    fun getDefectCode() {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","BAD")
        map.addProperty("USERNAME", Constant.CURRENT_USER)
        launchOnlyResult({
            val defectCode = defectRepository.getDefectCode(map)
            defectCode.BADCODE.forEach {
                defectDesc.add(it.NAME)
            }
            defectCode.BADLOCATION.forEach {
                defectPos.add(it.NAME)
            }
            defectCode.BADNUMBER.forEach {
                defectNum.add(it.NAME)
            }
        })
    }

    fun addDefect(code : String,pos : String,num : String,path : String){
        val fileName = finBatchItems[0].LOTID + FreeApi_DateUtils.getNowStringDate("yyyyMMddHHmmssSSS")
        if (path.isEmpty()){
            saveDefect(code,pos,num,"")
        }else{
            thread {
                if (SmbFileUtils.smbUpload(
                        path,
                        fileName
                    )
                ) {
                    saveDefect(code,pos,num,"${SmbFileUtils.remoteUrl}$fileName.jpg")
                }else{
                    handler.post {
                        defUI.toastEvent.value = ToastMessageBean("图片上传失败",false)
                        defUI.callObserve.value = CallObserveBean(0,"FAIL")
                    }
                }
            }
        }
    }

    fun deleteDefect(item : DefectEntity.DefectInfoEntity){
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","PICDEL")
        map.addProperty("BADRRN",item.BADRRN)
        launchOnlyResult({
            defectRepository.saveFinCheck(map)
            currentDefectItems.remove(item)
        })
    }

    private fun saveDefect(code : String, pos : String, num : String, path : String){
        val entity = DefectEntity.DefectInfoEntity()
        entity.BADDES = code
        entity.BADLOC = pos
        entity.BADQTY = num
        entity.URL = path
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","SAVETRACKPIC")
        map.addProperty("OBJECTRRN",finBatchItems[0].OBJECTRRN)
        map.add("BADINFO", JsonParser().parse(Gson().toJson(entity)).asJsonObject)
        launchOnlyResult({
            defectRepository.saveFinCheck(map)
            defUI.toastEvent.value = ToastMessageBean("添加成功",true)
            defUI.callObserve.value = CallObserveBean(0,"SUCCESS")
        })

    }


}